/*
 * @# SendEmailUtils.java 2011-7-12 上午11:11:24
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.px.utils;

import org.apache.commons.mail.DefaultAuthenticator;
import org.apache.commons.mail.EmailException;
import org.apache.commons.mail.HtmlEmail;
import org.apache.log4j.Logger;

/**
 * 发送电子邮件工具类
 * @author tianqingsen
 */
public class SendEmailUtils {

	private static Logger log = Logger.getLogger(SendEmailUtils.class);

	/**
	 * 发送电子邮件
	 * @param to 接收者邮箱地址
	 * @param emailSubject 邮件主题
	 * @param emailContent 邮件内容
	 * @param contentType 邮件内容类型
	 */
	public static void send(String to, String emailSubject, String emailContent, String contentType) {

		HtmlEmail htmlEmail = new HtmlEmail();

		try {
			// 设置接收邮件的邮件服务器
			htmlEmail.setHostName(AppPropReader.getProperties("email.hostName"));
			// 用户名密码验证
			htmlEmail.setAuthenticator(new DefaultAuthenticator(AppPropReader.getProperties("send.email.userName"),
					AppPropReader.getProperties("send.email.password")));
			htmlEmail.addTo(to);
			htmlEmail.setFrom(AppPropReader.getProperties("send.email.adrress"));
			htmlEmail.setSubject(emailSubject);
			htmlEmail.setMsg(emailContent);
			htmlEmail.setContent(emailContent, contentType);
			htmlEmail.send();
		} catch (EmailException e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("邮件服务器连接失败，请稍后再试...", e);
		} catch (RuntimeException e) {
			log.error(e.getMessage(), e);
			throw new RuntimeException("系统异常，请稍后再试...", e);
		}
	}

	/**
	 * 发送HTML格式电子邮件
	 * @param to 接收者邮箱地址
	 * @param emailSubject 邮件主题
	 * @param emailContent 邮件内容
	 */
	public static void sendHtml(String to, String emailSubject, String emailContent) {
		send(to, emailSubject, emailContent, "text/html;charset=utf-8");
	}

	/**
	 * 发送文本格式电子邮件
	 * @param to 接收者邮箱地址
	 * @param emailSubject 邮件主题
	 * @param emailContent 邮件内容
	 */
	public static void sendText(String to, String emailSubject, String emailContent) {
		send(to, emailSubject, emailContent, "text/plain;charset=utf-8");
	}
}
